from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict, Union

from weather import ChatService, WeatherService, format_weather_data, WeatherInfo

app = FastAPI(
    title="智能助手API",
    description="提供智能对话服务，支持天气查询和普通聊天",
    version="1.0.0"
)

# 初始化服务
weather_service = WeatherService()
chat_service = ChatService()


class ChatRequest(BaseModel):
    message: str


class ChatResponse(BaseModel):
    response: str
    type: str
    details: Dict = {}


@app.post("/chat", response_model=ChatResponse, summary="智能对话接口")
async def chat(request: ChatRequest):
    """
    统一的智能对话接口，自动判断是天气查询还是普通对话
    
    - **message**: 用户输入的消息
    
    返回:
    - **response**: 助手的回复
    - **type**: 对话类型 (weather/chat)
    - **details**: 详细信息（天气查询时包含天气数据）
    """
    try:
        # 处理用户输入，识别意图
        intent = chat_service.process_message(request.message)

        if intent["type"] == "weather":
            # 处理天气查询
            weather_result = weather_service.get_weather(intent["city"])
            if isinstance(weather_result, WeatherInfo):
                weather_data = format_weather_data(weather_result)
                response = weather_service.describe_weather(intent["city"], weather_data)
                return ChatResponse(
                    response=response,
                    type="weather",
                    details={
                        "city": intent["city"],
                        "weather_data": weather_data
                    }
                )
            else:
                return ChatResponse(
                    response=weather_result,
                    type="error",
                    details={"error": weather_result}
                )
        else:
            # 处理普通对话
            response = chat_service.chat_response(intent["message"])
            return ChatResponse(
                response=response,
                type="chat",
                details={}
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
